package com.raymond.config;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import com.raymond.entity.commons.BaseEnum;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;

import java.io.IOException;

/**
 * desc-整型枚举反序列化
 *
 * @author houmenghe
 * @date 2025/04/21 20:38
 **/
public class CustomerIntegerEnumDeserializer<E extends Enum<?> & BaseEnum> extends JsonDeserializer<E> {

    @Override
    public E deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
        final JsonNode node = jsonParser.getCodec().readTree(jsonParser);
        Class type = BeanUtils.findPropertyType(jsonParser.getCurrentName(), jsonParser.getCurrentValue().getClass());
        if (StringUtils.isNotEmpty(node.asText())) {
            int code = node.asInt();
            return (E) BaseEnum.getEnumByValue(type, code);
        } else {
            return null;
        }
    }
}
